package dparish.client.view.impl;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import dparish.client.common.widgets.LabeledValueWidget;
import dparish.client.proxy.StudentProxy;
import dparish.client.view.StudentView;

public class StudentViewImpl extends Composite implements StudentView{


	@UiField Button saveButton;
	@UiField Button cancelButton;
	@UiField TextBox firstName;
	@UiField TextBox lastName;
	@UiField TextBox email;
	@UiField Label idLabel;
	@UiField LabeledValueWidget studentForm;
	
	private StudentProxy student;
	private StudentView.Presenter<StudentProxy> presenter;
	
	private static StudentViewUiBinder uiBinder = GWT
			.create(StudentViewUiBinder.class);

	@UiTemplate("StudentView.ui.xml")
	interface StudentViewUiBinder extends UiBinder<Widget, StudentViewImpl> {
	}

	public StudentViewImpl() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@Override
	public void setPresenter(StudentView.Presenter<StudentProxy> p) {
		this.presenter = p;
	}

	@Override
	public void render() {
		student = presenter.getEntity();
		if (student == null) {
			return;
		}
		firstName.setText(student.getFirstName());
		lastName.setText(student.getLastName());
		email.setText(student.getEmail());
		idLabel.setText(student.getId() + "");
	}
	
	@UiHandler ("cancelButton")
	public void handleCancelClick (ClickEvent event) {
		presenter.onCancelEvent();
	}
	
	@UiHandler ("saveButton")
	public void handleSaveClick (ClickEvent event) {
		student.setEmail(email.getText());
		student.setFirstName(firstName.getText());
		student.setLastName(lastName.getText());
		presenter.onSaveEvent(student);
	}


	@Override
	public void saveCallback(String message) {
		if (message == null || message.isEmpty()) {
			return;
		}
		else {
			Window.alert("There was an error with the save:" + message);
		}
	}

}
